package com.wuqing.mybatisredisdemo.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author luwenhao
 * @create 2021/8/3
 */
@Component
public class SpringContextHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext = applicationContext;
    }

    public static <T> T getBean(Class<T> type) {
        assertContextInjected();
        return applicationContext.getBean(type);
    }

    public static Object getBean(String beanName){
        assertContextInjected();

        return applicationContext.getBean(beanName);
    }

    public static void assertContextInjected() {

        if (applicationContext == null) {
            throw new RuntimeException("applicationContext未注入");
        }
    }


}
